package com.bachelor.community.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.bachelor.community.annotation.UnInterception;
import com.bachelor.community.model.entity.User;
import com.bachelor.community.service.intf.UserService;
import com.bachelor.community.utils.ServiceException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("Method:OPTIONS");
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        UnInterception unInterception = method.getAnnotation(UnInterception.class);
        if (unInterception != null) {
            return true;
        }
        String token = StrUtil.removePrefix(request.getHeader("Authorization"), "Bearer ");
        // 如果不是映射到方法，则直接通过
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401", "无token，请重新登录");
        }
        String userId;
        try {
            JWT jwt = JWT.of(token);
            userId = jwt.getPayload("user_id").toString();
        } catch (Exception e) {
            throw new ServiceException("401", "token验证失败，请重新登录");
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException("401", "用户不存在，请重新登录");
        }
        byte[] key = user.getPassword().getBytes();
        if (JWT.of(token).setKey(key).verify()) {
            return true;
        } else {
            throw new ServiceException("401", "token验证失败，请重新登录");
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
